package in.hitmedia.test.sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BinarySearch 
{

	private Long[] read(String filename) throws IOException
	{
		
		BufferedReader br = new BufferedReader(new FileReader(filename));
		
		String line = null;
		
		List<Long> a = new ArrayList<Long>();
		while((line = br.readLine()) != null)
		{
			try
			{
				long parseLong = Long.parseLong(line.trim());
				a.add(parseLong);
			}
			catch (NumberFormatException nfe)
			{
				
			}
		}
		
		return a.toArray(new Long[a.size()]); 
	}
	
	
	
	private int binarySearch(final Long a[], final Long val, int start, int end)
	{
		if (start > end)
		{
			return -1;
		}
		int mid = (start+end)/2;
		
		if (val == a[mid])
		{
			return mid;
		}	
		else if (val < a[mid])
		{
			end = mid-1;
			return binarySearch(a, val, start, end);
		}
		else
		{
			start = mid + 1;
			return binarySearch(a, val, start, end);
		}
	}
	
	private static void print(Long a[])
	{
		for(int i=0; i < a.length; ++i)
		{
			System.out.print(a[i]+"\t");
			if ((i+1) %10 == 0)
			{
				System.out.println();
			}
		}
		System.out.println();
	}
	
	public void runBinarySearch (String in, String out)
	{
		try
		{
			Long[] inArray = {1L, 2L, 3L, 4L, 5L, 6L, 7L};
			//Long[] inArray = read(in);
			//print(inArray);
			
			long start = System.currentTimeMillis();
			System.out.println(""+binarySearch(inArray, 3L, 0, inArray.length-1));
			long end = System.currentTimeMillis();
			
			System.out.println("Time to process "+((end - start)) +" miliseconds.");
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(out));
			
			for (int i = 0; i < inArray.length; ++i)
			{
				bw.write(""+inArray[i]);
				bw.newLine();
			}
			bw.close();
			
			//print(inArray);
		}
		catch (Exception e)
		{
			System.out.println("Received exception"+ e);
		}
		
		
	}
	
	public static void main(String args[])
	{
		BinarySearch is = new BinarySearch();
		is.runBinarySearch(args[0], args[1]);
	}
	
}
